package top.z.work.framework.web.handler;

import jakarta.annotation.Nonnull;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import top.z.work.framework.common.pojo.R;
import top.z.work.framework.web.util.WebFrameworkUtil;

/**
 * 全局响应结果ResponseBody处理器
 */
@ControllerAdvice
public class GlobalResponseBodyHandler implements ResponseBodyAdvice<R> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        if (returnType.getMethod() == null) {
            return false;
        }
        // 只拦截返回结果为 CommonResult 类型
        return returnType.getMethod().getReturnType() == R.class;
    }

    @Override
    public R<?> beforeBodyWrite(
            R body,
            @Nonnull MethodParameter returnType,
            @Nonnull MediaType selectedContentType,
            @Nonnull Class<? extends HttpMessageConverter<?>> selectedConverterType,
            @Nonnull ServerHttpRequest request,
            @Nonnull ServerHttpResponse response
    ) {
        // 记录 Controller 结果
        WebFrameworkUtil.setResult(((ServletServerHttpRequest) request).getServletRequest(), (R<?>) body);
        return body;
    }
}
